package com.tqyan.util;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;

/**
 * 雪花算法
 * <p> <功能详细描述> </p>
 *
 * @author 陈晨
 * @version 1.0
 * @date 2023/2/15
 */
public class SnowflakeUtils {
    // 起始的时间戳
    private final static long START_STAMP = 1680000000000L;

    // 每一部分占用的位数
    private final static long SEQUENCE_BIT = 12; // 序列号占用的位数
    private final static long MACHINE_BIT = 5; // 机器标识占用的位数
    private final static long DATACENTER_BIT = 5; // 数据中心占用的位数

    // 每一部分的最大值
    private final static long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);
    private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
    private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);

    // 每一部分向左的位移
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

    private static long datacenterId = 0L; // 数据中心
    private static long machineId = 0L; // 机器标识
    private static long sequence = 0L; // 序列号
    private static long lastStamp = -1L; // 上一次时间戳

    public static void init(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
        }
        SnowflakeUtils.datacenterId = datacenterId;
        SnowflakeUtils.machineId = machineId;
    }

    static {
        try {
            // datacenterId
            String hostname = InetAddress.getLocalHost().getHostName();
            long datacenterId = Math.abs(hostname.hashCode()) % 32;
            System.out.println("MAX_DATACENTER_NUM: " + MAX_DATACENTER_NUM);
            System.out.println("Hostname: " + datacenterId);
            // machineId
            String jvmName = ManagementFactory.getRuntimeMXBean().getName();
            long machineId = Long.parseLong(jvmName.split("@")[0]) % 32;
            System.out.println("MAX_MACHINE_NUM: " + MAX_MACHINE_NUM);
            System.out.println("PID: " + machineId);
            // init
            init(datacenterId, machineId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static synchronized long nextId() {
        long currentStamp = getNewStamp();
        if (currentStamp < lastStamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id");
        }
        if (currentStamp == lastStamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                currentStamp = getNextMill();
            }
        } else {
            sequence = 0L;
        }
        lastStamp = currentStamp;
        return (currentStamp - START_STAMP) << TIMESTAMP_LEFT
                | datacenterId << DATACENTER_LEFT
                | machineId << MACHINE_LEFT
                | sequence;
    }

    private static long getNextMill() {
        long mill = getNewStamp();
        while (mill <= lastStamp) {
            mill = getNewStamp();
        }
        return mill;
    }

    private static long getNewStamp() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) throws Exception {
        System.out.println("CurrTime: " + System.currentTimeMillis());
        for (int i = 0; i < 10; i++) {
            System.out.println(SnowflakeUtils.nextId());
        }
        System.out.println();

//        SnowflakeUtils.START_STAMP = 0;
        for (int i = 0; i < 10; i++) {
            System.out.println(SnowflakeUtils.nextId());
        }
    }

}


